package com.xmy.cultivate.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.EnrollStagePeriod;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.StudentAccount;
import io.swagger.models.auth.In;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Pattern;

public class CommonUtil {

    /**
     * 判断两个值的季度相差多少
     */
    public static Integer diffQuarter(Map<String,Integer> map){
        Integer oldYear = map.get("oldYear");
        Integer oldNum = map.get("oldNum");
        Integer newYear = map.get("newYear");
        Integer newNum = map.get("newNum");

        Integer diffYear = newYear - oldYear;
        Integer diffNum = (newYear - oldYear) * 4 + newNum - oldNum;

        return diffNum;
    }

    public static int getNotSimple(int[] param, int len) {
        Random rand = new Random();
        for (int i = param.length; i > 1; i--) {
            int index = rand.nextInt(i);
            int tmp = param[index];
            param[index] = param[i - 1];
            param[i - 1] = tmp;
        }
        int result = 0;
        for (int i = 0; i < len; i++) {
            result = result * 10 + param[i];
        }
        return result;
    }

    public static int getReceiptNo(){
        int [] randMath = new int[]{1,2,3,4,5,6,7,8,9,0};
        Integer randReceiptNo = getNotSimple(randMath,7);
        return randReceiptNo;
    }

    /**
     * 获取考试名称
     * @param id
     * @return
     */
    public static String getExamNameForId(Integer id){
        String[] dataArr = new String[]{"","期中","期中摸底","期末","期末摸底","市模拟"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    /**
     * 获取学期
     * @param id
     * @return
     */
    public static String getQuarterNameForId(Integer id){
        String[] dataArr = new String[]{"","寒假班","春季班","暑假班","秋季班"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    /**
     * 获取年级
     * @param id
     * @return
     */
    public static String getYearClassNameForId(Integer id){
        String[] dataArr = new String[]{"幼儿园","一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    /**
     * 获取科目
     * @param id
     * @return
     */
    public static String getSubjectsNameForId(Integer id){
        String[] dataArr = new String[]{"","英语","数学","物理","语文"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    /**
     * 获取科目
     * @param id
     * @return
     */
    public static String getLessonTypeName(Integer id){
        String[] dataArr = new String[]{"","精品课","智能课","刷题班","教学艺术"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    public static String getCourseTypeName(Integer id){
        String[] dataArr = new String[]{"","正常排课","","请假补课","调课","消课","缺课补课"};
        String name = "";
        if(id>=0 && id<dataArr.length){
            name =dataArr[id];
        }
        return name;
    }

    /**
     * 获取年级段，如少儿,小学，初中,高中（0，1，2年级属于少儿）
     * @return
     */
    public static Integer getGradeSection(Integer yearClassId){
        Integer gradeSection = 100;//默认100
        if (yearClassId <=2){
            gradeSection = 0;
        }else if (yearClassId >2 && yearClassId<=6){
            gradeSection = 1;
        }else if (yearClassId>6 && yearClassId<=9){
            gradeSection = 2;
        }else if (yearClassId>9 && yearClassId<=12){
            gradeSection = 3;
        }
        return gradeSection;
    }
    /**
     * 获取年级段，如幼儿圆,小学，初中,高中(0属于少儿)
     * @return
     */
    public static Integer getGradeSectionForYearClassId(Integer yearClassId){
        Integer gradeSection = 100;//默认100
        if (yearClassId ==0){
            gradeSection = 0;
        }else if (yearClassId >0 && yearClassId<=6){
            gradeSection = 1;
        }else if (yearClassId>6 && yearClassId<=9){
            gradeSection = 2;
        }else if (yearClassId>9 && yearClassId<=12){
            gradeSection = 3;
        }
        return gradeSection;
    }



    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 判断是否是整数或者是小数
     * @param str
     * @return
     */
    public static boolean validateNumber(String str) {
        if(StringUtils.isBlank(str)) {
            return false;
        }// 说明一下的是该正则只能识别4位小数；如果不限制小数位数的话，写成[+-]?[0-9]+(\\.[0-9]+)?就可以了
        return str.matches("[+-]?[0-9]+(\\.[0-9]{1,4})?");
    }

    public static String chToPinyin(String chinese){
        String pinyin="";
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
        for (char c : chinese.toCharArray()) {
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    pinyin += pinyinArray[0];
                } else {
                    pinyin += c;
                }
            } catch (Exception e) {
                pinyin += c;
            }
        }
        return pinyin;
    }

    /**
     * 获取学段id
     * @param yearClassId
     * @return
     */
    public static Integer getGradeSectionId(Integer yearClassId){
        //yearClassId:少儿:0,1,2;小学:3,4,5,6;初中7,8,9;高中:10,11,12

        Integer[][] arr={{0,1,2},{3,4,5,6},{7,8,9},{10,11,12}};
        Integer rs = null;
        for (int i=0;i<arr.length;i++){
            Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr[i]));
            if (set.contains(yearClassId)){
                rs = i;
                break;
            }
        }
        return rs;
    }

    /**
     * 获取上次期末
     * @param yearPart
     * @param quarterNum
     * @return
     */
    public static Quarter getUpQuarterForTerm(Integer yearPart,Integer quarterNum){
        Integer upYearPart = yearPart;
        Integer upQuarterNum = 0;
        Integer upExamNum = 3;//期末
        if (quarterNum.equals(2)){
            upQuarterNum =4;
            upYearPart = upYearPart - 1;
        }else if (quarterNum.equals(4)){
            upQuarterNum =2;
        }else if(quarterNum.equals(1)){
            upQuarterNum =4;
            upYearPart = upYearPart - 1;
        }else if(quarterNum.equals(3)){
            upQuarterNum =2;
        }
        String name = getQuarterNameForId(upQuarterNum);
        Quarter quarter = new Quarter();
        quarter.setAliasName(name);
        quarter.setYearPart(upYearPart);
        quarter.setNum(upQuarterNum);
        quarter.setSort(upExamNum);
        return quarter;
    }

    /**
     * 获取下一学期
     * @param yearPart
     * @param quarterNum
     * @return
     */
    public static Quarter getNextQuarter(Integer yearPart, Integer quarterNum){
        Integer nextYearPart = yearPart;
        Integer nextQuarterNum = 0;
        if (quarterNum.equals(4)){
            nextQuarterNum =1;
            nextYearPart = nextYearPart + 1;
        }else {
            nextQuarterNum = quarterNum+1;
        }
        Quarter quarter = new Quarter();
        quarter.setYearPart(nextYearPart);
        quarter.setNum(nextQuarterNum);
        return quarter;
    }

    /**
     * 获取上一学期
     * @param yearPart
     * @param quarterNum
     * @return
     */
    public static Quarter getUpQuarter(Integer yearPart, Integer quarterNum){
        Integer upYearPart = yearPart;
        Integer upQuarterNum = 0;
        if (quarterNum.equals(1)){
            upQuarterNum =4;
            upYearPart = upYearPart - 1;
        }else {
            upQuarterNum = quarterNum-1;
        }
        Quarter quarter = new Quarter();
        quarter.setYearPart(upYearPart);
        quarter.setNum(upQuarterNum);
        return quarter;
    }

    /**
     * 获取对应学段的年级
     * @param gradeSection
     * @return
     */
    public static List<Integer> getYearClassIdForGradeSection(Integer gradeSection){

        List<Integer> yearClassIdList = new ArrayList<>();

        if (gradeSection.equals(0)){
            for (int i = 0; i <=2; i++) {
                yearClassIdList.add(i);
            }
        }else if (gradeSection.equals(1)){
            for (int i = 3; i <=6; i++) {
                yearClassIdList.add(i);
            }
        }else if (gradeSection.equals(2)){
            for (int i = 7; i <=9; i++) {
                yearClassIdList.add(i);
            }
        }else if (gradeSection.equals(3)){
            for (int i = 10; i <=12; i++) {
                yearClassIdList.add(i);
            }
        }else {
            yearClassIdList.add(-1);
        }
        return yearClassIdList;
    }

    /**
     * 密码是否是正序或反序连续4位及以上
     * @param pwd
     * @return true为正确，false为错误。
     */
    public static boolean isPasswordContinuous(String pwd) {
        int count = 0;//正序次数
        int reverseCount = 0;//反序次数
        String[] strArr = pwd.split("");
        for(int i = 1 ; i < strArr.length-1 ; i ++) {//从1开始是因为划分数组时，第一个为空
            if(isPositiveContinuous(strArr[i],strArr[i+1])) {
                count ++;
            }
            else {
                count = 0;
            }
            if(isReverseContinuous(strArr[i],strArr[i+1])) {
                reverseCount ++;
            }
            else {
                reverseCount = 0;
            }
            if(count > 2 || reverseCount > 2) break;
        }
        if(count > 2 || reverseCount > 2) return false;
        return true;
    }

    /**
     * 是否是正序连续
     * @param str1
     * @param str2
     * @return
     */
    public static boolean isPositiveContinuous(String str1 , String str2) {
        if(str2.hashCode() - str1.hashCode() == 1) return true;
        return false;
    }
    /**
     * 是否是反序连续
     * @param str1
     * @param str2
     * @return
     */
    public static boolean isReverseContinuous(String str1 , String str2) {
        if(str2.hashCode() - str1.hashCode() == -1) return true;
        return false;
    }
    /**
     * - 字母区分大小写，可输入符号<br/>
     - 密码必须同时包含字母和数字<br/>
     - 密码长度8-20位<br/>
     - 密码中不能存在连续4个及以上的数字或字母（如：1234、7654、abcd、defgh等）<br/>
     - 密码中不能包含个人手机号后4位<br/>
     @author Miaozz.
     @param phone 手机号码
      * @param password 密码
     * @return true为正确，false为错误
     */
    public static boolean isPasswordAvailable(String phone,String password) {
        /*String last4No = phone.substring(phone.length()-4);
        String str = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";//必须同时包含字母数字并且是8-20位
        if(!password.contains(last4No) && password.matches(str)) {
            return isPasswordContinuous(password);
        }*/
        return isPasswordContinuous(password);
    }

    public static String replaceGradeName(String gradeName,String teacherName, String studentName, String subjectsName) {
        String keyword1 = gradeName;
        if (keyword1.contains("【" + teacherName + "】")) {
            keyword1 = keyword1.replace("【" + teacherName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains("【" + subjectsName + "】")) {
            keyword1 = keyword1.replace("【" + subjectsName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains(teacherName)) {
            keyword1 = keyword1.replace(teacherName, studentName);
            keyword1 += subjectsName;
        } else {
            keyword1 = "【" + teacherName + "】" + subjectsName + keyword1;
        }
        return keyword1;
    }

    public static String getYearClassIdsForGradeSection(Integer gradeSection){
        String[] dataArr = new String[]{"0,1,2","3,4,5,6","7,8,9","10,11,12"};
        String yearClassIds="";
        if(gradeSection>=0 && gradeSection<dataArr.length){
            yearClassIds =dataArr[gradeSection];
        }
        return yearClassIds;
    }

    public static int generate4DigitNumber() {
        Random random = new Random();
        int num = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数
        return num;
    }

    public static String getGradeSectionNameForId(Integer id) {
        String[] dataArr = new String[]{"少儿", "小学", "初中", "高中"};
        String name = "";
        if (id >= 0 && id < dataArr.length) {
            name = dataArr[id];
        }
        return name;
    }

    public static String getWeekForId(Integer id) {
        String[] dataArr = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        String name = "";
        if (id >= 0 && id < dataArr.length) {
            name = dataArr[id];
        }
        return name;
    }

    /**
     * 判断日期是否冲突、重叠
     */
    public static boolean hasDateConflict(List<EnrollStagePeriod> periods) {
        for (int i = 0; i < periods.size(); i++) {
            LocalDate startDate1 = periods.get(i).getStartDate();
            LocalDate endDate1 = periods.get(i).getEndDate();

            for (int j = i + 1; j < periods.size(); j++) {
                LocalDate startDate2 = periods.get(j).getStartDate();
                LocalDate endDate2 = periods.get(j).getEndDate();

                if (!endDate1.isBefore(startDate2) && !endDate2.isBefore(startDate1)) {
                    return true; // 存在冲突
                }
            }
        }
        return false; // 没有冲突
    }

    /**
     * 学期
     * 往上1个学期，或者往上0个学期
     * @param quarterNum
     * @param upNum
     * @return
     */
    public Integer getUpYearForId(Integer yearPart,Integer quarterNum, Integer upNum) {
        Integer upYearPart = yearPart;

        if (quarterNum.equals("2")) {
            upYearPart = upYearPart - 1;
        } else if (quarterNum.equals("4")) {
        } else if (quarterNum.equals("1")) {
            upYearPart = upYearPart - 1;
        }
        return upYearPart;
    }

    /**
     * 获取课程类型
     * @param subjectId
     * @param lessonType
     * @return
     */
    public static String buildSubjectLessonTypeKey(Long subjectId, Integer lessonType) {
        String subjectName = "";
        if (subjectId == 1L && lessonType == 1) {
            subjectName = "英语精品课";
        } else if (subjectId == 1L && lessonType == 2) {
            subjectName = "英语智能课";
        } else if (subjectId == 2L && lessonType == 1) {
            subjectName = "数学精品课";
        } else if (subjectId == 2L && lessonType == 3) {
            subjectName = "数学刷题班";
        } else if (subjectId == 3L && lessonType == 1) {
            subjectName = "物理精品课";
        } else if (subjectId == 3L && lessonType == 3) {
            subjectName = "物理刷题班";
        }
        return subjectName;
    }

    /**
     * 获取拉卡拉订单号
     * @return
     */
    public static String getLklOrderNo(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        String milliseconds = String.valueOf(System.currentTimeMillis() % 1000000000);
        StringBuilder sb = new StringBuilder(timestamp);
        while (milliseconds.length() < 9) {
            milliseconds = "0" + milliseconds;
        }
        sb.append(milliseconds);
        return sb.toString();
    }


    /**
     * 不足位数，补零
     * @param number
     * @param length
     * @return
     */
    public static String padZeroes(int number, int length) {
        return String.format("%0" + length + "d", number);
    }

}
